package com.shenjies88.practice.reactor.hold;

import cn.hutool.core.util.RandomUtil;
import com.shenjies88.practice.reactor.wrapper.SelectorWrapper;

import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shenjies88
 * @since 2022/12/7/19:48
 */
public class SelectorWrapperHold {
    private static final int SELECTOR_WRAPPER_SIZE = 5;
    private static List<SelectorWrapper> selectorWrappersList = null;

    private SelectorWrapperHold() {

    }

    public synchronized static void init() {
        if (selectorWrappersList != null && selectorWrappersList.size() > 0) {
            return;
        }
        selectorWrappersList = new ArrayList<>();
        for (int i = 0; i < SELECTOR_WRAPPER_SIZE; i++) {
            var selectorWrapper = new SelectorWrapper();
            selectorWrapper.init(i);
            selectorWrappersList.add(selectorWrapper);
        }
    }

    public static void register(SocketChannel socketChannel) {
        var index = RandomUtil.randomInt(10, 10000) % SELECTOR_WRAPPER_SIZE;
        var selectorWrapper = selectorWrappersList.get(index);
        selectorWrapper.queue(socketChannel);
    }
}
